package com.sk.bilibili.websocket;

import com.sk.bilibili.bean.Danmu;
import com.sk.bilibili.decoder.DanmuDecoder;
import com.sk.bilibili.encoder.JsonEncoder;
import com.sk.bilibili.service.VideoSocketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

/**
 * @author 邵康
 * @date 2021/12/2 14:07
 */
@Component
@ServerEndpoint(value = "/video/{videoId}",encoders = JsonEncoder.class,
        decoders = DanmuDecoder.class)
public class VideoSocket{

    private static VideoSocketService videoSocketService;
    private Integer videoId;

    @Autowired
    public void setVideoSocketService(VideoSocketService videoSocketService) {
        VideoSocket.videoSocketService = videoSocketService;
    }

    @OnMessage
    public void onMessage(Danmu danmu){
        videoSocketService.broadcastDanmu(videoId,danmu);
    }

    @OnOpen
    public void onOpen(@PathParam("videoId")Integer videoId,Session session){
        videoSocketService.addNew(videoId,session);
        this.videoId=videoId;
    }

    @OnError
    public void onError(Throwable e){
        e.printStackTrace();
    }

    @OnClose
    public void onClose(Session session){
        videoSocketService.removeOld(videoId,session);
    }

}
